package com.zijie.system.controller.system;

import cn.dev33.satoken.annotation.SaIgnore;
import com.zijie.common.core.exception.ServiceException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.time.LocalTime;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
 * @author 喻字杰与刘宝宝
 */

@RestController
public class SseController {
    private static final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();

    // 浏览器连接入口
    @GetMapping(value="/sse-connect",produces = "text/event-stream")
    public SseEmitter connect(@RequestParam String userId) {
        SseEmitter emitter = new SseEmitter(30 * 60 * 1000L); // 30分钟超时
        emitters.put(userId, emitter);
        // 发送欢迎消息
        try {
            emitter.send(SseEmitter.event()
                    .name("welcome")
                    .data("🎉 连接成功！欢迎使用 SSE 服务"));
            //当前在线
            System.out.println("当前在线人数：" + emitters.size());
        } catch (IOException e) {
            throw new ServiceException("连接失败");
        }

        return emitter;
    }

    //关闭连接
    @GetMapping("/sse-close")
    public void close(@RequestParam String userId) {
        SseEmitter emitter = emitters.get(userId);
        if (emitter != null) {
            emitter.complete();
            emitters.remove(userId);
            System.out.println("用户 " + userId + " 已断开连接，当前在线人数：" + emitters.size());
        }
    }

    // 模拟推送服务,每2s推送一次数据


    //@Scheduled(fixedRate = 2000)
    public void pushData() {
        emitters.forEach((userId, emitter) -> {
            try {
                String json = String.format(
                        "{\"time\": \"%s\", \"value\": %.2f}",
                        LocalTime.now(), Math.random() * 100
                );
                System.out.println("推送消息=》"+json);

                // 构建符合SSE格式的消息
                emitter.send(SseEmitter.event()
                        .id(UUID.randomUUID().toString())
                        .name("system-metrics")
                        .data(json));
            } catch (IOException e) {
                emitters.remove(userId);
            }
        });
    }
}
